﻿Imports System.ComponentModel
Imports System.IO
Imports Junction
Imports System.Text.RegularExpressions
Imports System.Collections.Specialized

Public Class FormMain


    Sub fillFolderListColumns()
        With ListViewJunctionItems

            With .Columns
                .Clear()
                .Add("Name", 200)
                .Add("Source", 200)
                .Add("Target", 200)
                .Add("Folder", 200)

            End With
        End With
    End Sub
    Sub fillJunctionFolderList()
        Dim source$ = TextBoxSourceFolder.Text
        If Trim(source).Length = 0 Then Exit Sub

        TextBoxSourceFolder.BackColor = System.Drawing.SystemColors.Window
        ErrorProvider.SetError(TextBoxSourceFolder, Nothing)

        fillFolderListColumns()
        ListViewJunctionItems.Items.Clear()

        If Not Directory.Exists(source) Then
            TextBoxSourceFolder.BackColor = Color.LightPink
            ErrorProvider.SetError(TextBoxSourceFolder, "Klasör bulunamadı [" & source & "]")
            Exit Sub
        End If


        With ListViewJunctionItems

            Dim sourceDir As New DirectoryInfo(TextBoxSourceFolder.Text)
            For Each item As DirectoryInfo In sourceDir.GetDirectories

                Dim liImageIndex%
                Dim ats = item.Attributes
                If ats = FileAttributes.Directory Then
                    liImageIndex = 0
                ElseIf ats = FileAttributes.Directory Or FileAttributes.ReparsePoint Then
                    liImageIndex = 1

                End If

                Dim targetName$ = ""
                Try
                    targetName = JunctionPoint.GetSymbolicLinkTarget(item)
                Catch ex As Win32Exception
                    Debug.Write(ex.Message)
                End Try

                Dim li = .Items.Add(item.Name, liImageIndex)
                If liImageIndex = 1 Then li.BackColor = Color.LightYellow

                li.SubItems.Add(item.FullName)
                li.SubItems.Add(targetName)
                li.SubItems.Add(item.Parent.FullName)


            Next
            For Each col As ColumnHeader In .Columns
                col.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)

            Next
        End With
    End Sub
    Private Sub ButtonSelectDir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSelectDir.Click

        If SourceFolderBrowserDialog.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
            TextBoxSourceFolder.Text = SourceFolderBrowserDialog.SelectedPath
            prepareSelectedTab()
        End If

    End Sub

    Private Sub TextBoxSourceFolder_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBoxSourceFolder.KeyDown
        If e.KeyCode = Keys.Enter Then
            prepareSelectedTab()
        End If
    End Sub

    Private Sub FormMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'loadFilterPresets()
        prepareSelectedTab()
    End Sub
    Private Sub loadFilterPresets()
        Junctions.My.Settings.Reload()
         
        Dim data = Junctions.My.MySettings.Default.FilePatterns
        If data Is Nothing Then
            data = New StringCollection
        End If
        Dim src(data.Count - 1) As String
        data.CopyTo(src, 0)
        Dim MySource As New AutoCompleteStringCollection()
        MySource.AddRange(src)
        TextBoxFilter.AutoCompleteCustomSource = MySource
        TextBoxFilter.AutoCompleteSource = AutoCompleteSource.CustomSource
    End Sub
    Private Sub ReloadJunctionFolderList(ByVal sender As System.Object, ByVal e As System.EventArgs)
        fillJunctionFolderList()

    End Sub

#Region "Junction Pop Menu Helper"

    Private Sub AddSource(ByVal sender As System.Object, ByVal e As System.EventArgs)


        Dim source$ = TextBoxSourceFolder.Text
        If Trim(source).Length = 0 Then Exit Sub

        Dim sourceParent As DirectoryInfo = New DirectoryInfo(source)
        Dim dlgNewFolder As New DialogSetFolder

        dlgNewFolder.TextBoxDir.Text = sourceParent.FullName

        Dim dlgRes As DialogResult = dlgNewFolder.ShowDialog(Me)
        If dlgRes = DialogResult.OK Then

            Dim newSource As String = Path.Combine(sourceParent.FullName, dlgNewFolder.TextBoxFolder.Text)
            Dim newSourceDir As DirectoryInfo = New DirectoryInfo(newSource)


            Dim dlgPreset$ = SourceFolderBrowserDialog.SelectedPath
            Dim dlg As DialogResult = SourceFolderBrowserDialog.ShowDialog()
            If dlg <> DialogResult.Cancel Then
                Dim newTarget$ = SourceFolderBrowserDialog.SelectedPath
                Dim newTargetDir As DirectoryInfo = New DirectoryInfo(newTarget)

                Dim li = ListViewJunctionItems.Items.Add(newSourceDir.Name, 1)
                li.BackColor = Color.Yellow

                li.SubItems.Add(newSourceDir.FullName)

                li.SubItems.Add(newTargetDir.FullName)
                li.SubItems.Add(source)


                Junction.JunctionPoint.Create(newSource, newTargetDir.FullName, False)


            End If

            SourceFolderBrowserDialog.SelectedPath = dlgPreset





        End If

    End Sub
    Private Sub ChangeToFolder(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim li As ListViewItem = ListViewJunctionItems.FocusedItem
        Dim source$ = li.SubItems(1).Text
        Dim target$ = li.SubItems(2).Text
        Dim sourceDir As DirectoryInfo = New DirectoryInfo(source)
        
        Dim ats = sourceDir.Attributes

         
         
        Junction.JunctionPoint.Delete(sourceDir.FullName)
        Directory.CreateDirectory(sourceDir.FullName)
            


        li.ImageIndex = 0


    End Sub
    Private Sub ChangeToParsePoint(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim li As ListViewItem = ListViewJunctionItems.FocusedItem
        Dim source$ = li.SubItems(1).Text
        Dim target$ = li.SubItems(2).Text
        Dim sourceDir As DirectoryInfo = New DirectoryInfo(source)

        Dim ats = sourceDir.Attributes
retry:
        If sourceDir.GetFileSystemInfos.Count > 0 Then
            If MsgBox("Klasör alt klasör veya dosyalar içeriyor", MsgBoxStyle.RetryCancel, "Hata oluştu") = MsgBoxResult.Cancel Then
                Exit Sub

            Else
                GoTo retry
            End If

        End If

        Directory.Delete(sourceDir.FullName)
        Junction.JunctionPoint.Create(sourceDir.FullName, target, True)




        li.ImageIndex = 1

    End Sub
    Private Sub ChangeSource(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim li As ListViewItem = ListViewJunctionItems.FocusedItem
        Dim source$ = li.SubItems(1).Text
        Dim target$ = li.SubItems(2).Text
        Dim sourceDir As DirectoryInfo = New DirectoryInfo(source)
        Dim sourceParentDir As DirectoryInfo = sourceDir.Parent
        Dim dlgNewFolder As New DialogSetFolder

        dlgNewFolder.TextBoxDir.Text = sourceParentDir.FullName
        dlgNewFolder.TextBoxFolder.Text = sourceDir.Name

        Dim ats = sourceDir.Attributes
         


        Dim dlgRes As DialogResult = dlgNewFolder.ShowDialog(Me)
        If dlgRes = DialogResult.OK Then

            Dim newSource As String = Path.Combine(sourceParentDir.FullName, dlgNewFolder.TextBoxFolder.Text)


             
                Directory.Delete(source)

                Junction.JunctionPoint.Create(newSource, target, False)



            li.SubItems(1).Text = newSource
        End If


    End Sub
    Private Sub ChangeTarget(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim li As ListViewItem = ListViewJunctionItems.FocusedItem
        Dim source$ = li.SubItems(1).Text
        Dim target$ = li.SubItems(2).Text


        Dim dlgPreset$ = SourceFolderBrowserDialog.SelectedPath
        Dim dlg As DialogResult = SourceFolderBrowserDialog.ShowDialog()
        If dlg <> DialogResult.Cancel Then
            Dim newTarget$ = SourceFolderBrowserDialog.SelectedPath
            Directory.Delete(source)

            Junction.JunctionPoint.Create(source, newTarget, False)
            li.SubItems(2).Text = newTarget

        End If

        SourceFolderBrowserDialog.SelectedPath = dlgPreset

    End Sub

    Private Sub DeleteSource(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim li As ListViewItem = ListViewJunctionItems.FocusedItem
        Dim source$ = li.SubItems(1).Text
        Dim target$ = li.SubItems(2).Text

        Dim dlg As MsgBoxResult = MsgBox("Bağlantı silinecek", MsgBoxStyle.ApplicationModal Or MsgBoxStyle.Information Or MsgBoxStyle.OkCancel Or MsgBoxStyle.DefaultButton2)
        If dlg <> DialogResult.Cancel Then

            Directory.Delete(source)
            li.Remove()

        End If


    End Sub





    Private Sub LoadJunctionPopMenu(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStripList.Opening
        Dim popMenu As ContextMenuStrip = sender

        popMenu.SuspendLayout()

        popMenu.Items.Clear()

        Dim lis = ListViewJunctionItems.SelectedItems
        If lis.Count > 0 Then


            Dim li As ListViewItem = ListViewJunctionItems.FocusedItem

            Dim source$ = li.SubItems(1).Text
            Dim target$ = li.SubItems(2).Text
          
            Dim item As New DirectoryInfo(source)
            Dim ats = item.Attributes


            If ats = FileAttributes.Directory Then
                Dim toParsePoint As New ToolStripMenuItem("Bağlantı Noktasına Çevir", Nothing, AddressOf ChangeToParsePoint)

                popMenu.Items.Add(toParsePoint)
            ElseIf ats = FileAttributes.Directory Or FileAttributes.ReparsePoint Then

                Dim toFolder As New ToolStripMenuItem("Klasöre Çevir", Nothing, AddressOf ChangeToFolder)

                popMenu.Items.Add(toFolder)

                Dim chSource As New ToolStripMenuItem("Kaynağı değiştir", Nothing, AddressOf ChangeSource)

                popMenu.Items.Add(chSource)

                Dim chTarget As New ToolStripMenuItem("Hedefi değiştir", Nothing, AddressOf ChangeTarget)
                popMenu.Items.Add(chTarget)

                popMenu.Items.Add(New ToolStripSeparator)

                Dim deleteSource As New ToolStripMenuItem("Sil", Nothing, AddressOf Me.DeleteSource)
                popMenu.Items.Add(deleteSource)
                 

            End If

        End If


        Dim addNew As New ToolStripMenuItem("Yeni Ekle", Nothing, AddressOf AddSource)
        popMenu.Items.Add(addNew)


        popMenu.Items.Add(New ToolStripSeparator)


        Dim refresh As New ToolStripMenuItem("Yenile", Nothing, AddressOf ReloadJunctionFolderList)
        popMenu.Items.Add(refresh)


        popMenu.ResumeLayout(True)
        e.Cancel = False

        'popMenu.Visible = True

    End Sub
#End Region




    Sub fillFileListColumns()
        With ListViewFileItems

            With .Columns
                .Clear()
                .Add("Name", 200)
                .Add("New Name", 200)
                .Add("Folder", 200)
                .Add("Report", 200)
            End With
        End With
    End Sub

    Sub fillFileList()
        Dim source$ = TextBoxSourceFolder.Text
        If Trim(source).Length = 0 Then Exit Sub

        TextBoxSourceFolder.BackColor = System.Drawing.SystemColors.Window
        ErrorProvider.SetError(TextBoxSourceFolder, Nothing)
        ErrorProvider.SetError(TextBoxFilter, Nothing)
        ErrorProvider.SetError(TextBoxReplace, Nothing)

        fillFileListColumns()
        ListViewFileItems.Items.Clear()

        If Not Directory.Exists(source) Then
            TextBoxSourceFolder.BackColor = Color.LightPink
            ErrorProvider.SetError(TextBoxSourceFolder, "Klasör bulunamadı [" & source & "]")
            Exit Sub
        End If


        With ListViewFileItems

            Dim sourceDir As New DirectoryInfo(TextBoxSourceFolder.Text)
            For Each item As FileInfo In sourceDir.GetFiles
                Dim newName$ = item.Name

                Dim pattern = Trim(TextBoxFilter.Text)

                If pattern.Length > 0 Then
                    Try
                        If Regex.IsMatch(item.Name, pattern, RegexOptions.IgnoreCase) = False Then
                            Continue For
                        End If
                    Catch ex As ArgumentException
                        ErrorProvider.SetError(TextBoxFilter, ex.Message)
                        Exit Sub
                    End Try



                    Dim replace$ = Trim(TextBoxReplace.Text)

                    If replace.Length > 0 Then
                        Try
                            newName = Regex.Replace(newName, pattern, replace, RegexOptions.IgnoreCase)
                        Catch ex As Exception
                            ErrorProvider.SetError(TextBoxReplace, ex.Message)
                            Exit Sub
                        End Try
                    End If

                End If

                Dim icon = IconFactory.GetIcon(item.FullName)
                Dim ext As String = item.Extension

                If imageListFiles.Images.ContainsKey(ext) = False Then
                    imageListFiles.Images.Add(ext, icon)
                End If


                Dim liImageIndex = imageListFiles.Images.IndexOfKey(ext)

                Dim ats = item.Attributes




                Dim li = .Items.Add(item.Name, liImageIndex)

                li.Checked = True

                li.SubItems.Add(newName)

                li.SubItems.Add(item.Directory.FullName)

                Dim newPath = New FileInfo(Path.Combine(item.Directory.FullName, newName))
                If String.Equals(newName, item.Name, StringComparison.CurrentCultureIgnoreCase) = False Then
                    If newPath.Exists Then
                        li.SubItems.Add("File already exists")
                    End If
                End If


            Next
            For Each col As ColumnHeader In .Columns
                col.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)

            Next
        End With
    End Sub
    Private Sub TabControl_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl.SelectedIndexChanged
        prepareSelectedTab()
    End Sub

    Private Sub prepareSelectedTab()
        Dim tabs As TabControl = TabControl
        If tabs.SelectedIndex = 1 Then
            fillFileList()
        Else
            fillJunctionFolderList()
        End If
    End Sub

    Private Sub TextBoxFilter_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBoxFilter.KeyDown
        If e.KeyCode = Keys.Enter Then
            'Junctions.My.Settings.Reload()
            'Dim txt = TextBoxFilter.Text
            'Dim data = Junctions.My.MySettings.Default.FilePatterns
            'If data Is Nothing Then
            '    data = New StringCollection
            'End If
            'If data.Contains(txt) = False Then
            '    data.Add(txt)
            '    Junctions.My.MySettings.Default.FilePatterns = data
            '    Junctions.My.Settings.Save()
            '    loadFilterPresets()
            'End If



            fillFileList()
        End If
    End Sub

    Private Sub ButtonPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonPreview.Click
        fillFileList()
    End Sub


    Private Sub TextBoxReplace_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBoxReplace.KeyDown
        If e.KeyCode = Keys.Enter Then
            fillFileList()
        End If
    End Sub

    Private Sub ButtonRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonRename.Click



        For Each li As ListViewItem In ListViewFileItems.Items
            If li.Checked = False Then Continue For

            Dim oldName = li.SubItems(0).Text
            Dim newName = li.SubItems(1).Text
            Dim sourceDir As New DirectoryInfo(li.SubItems(2).Text)


            Dim newFilePath = Path.Combine(sourceDir.FullName, newName)

            If File.Exists(newFilePath) Then
                If li.SubItems.Count <= 3 Then li.SubItems.Add("")

                li.SubItems(3).Text = "File already exists"
                Continue For
            End If

            Dim oldFile As New FileInfo(Path.Combine(sourceDir.FullName, oldName))
            oldFile.MoveTo(newFilePath)


        Next

        Exit Sub

        'With ListViewFileItems


        '    For Each item As FileInfo In sourceDir.GetFiles
        '        Dim newName$ = item.Name

        '        Dim pattern = Trim(TextBoxFilter.Text)

        '        If pattern.Length > 0 Then
        '            Try
        '                If Regex.IsMatch(item.Name, pattern, RegexOptions.IgnoreCase) = False Then
        '                    Continue For
        '                End If
        '            Catch ex As ArgumentException
        '                ErrorProvider.SetError(TextBoxFilter, ex.Message)
        '                Exit Sub
        '            End Try



        '            Dim replace$ = Trim(TextBoxReplace.Text)

        '            If replace.Length > 0 Then
        '                Try
        '                    newName = Regex.Replace(newName, pattern, replace, RegexOptions.IgnoreCase)
        '                Catch ex As Exception
        '                    ErrorProvider.SetError(TextBoxReplace, ex.Message)
        '                    Exit Sub
        '                End Try
        '            End If

        '        End If

        '        Dim icon = IconFactory.GetIcon(item.FullName)
        '        Dim ext As String = item.Extension

        '        If imageListFiles.Images.ContainsKey(ext) = False Then
        '            imageListFiles.Images.Add(ext, icon)
        '        End If


        '        Dim liImageIndex = imageListFiles.Images.IndexOfKey(ext)

        '        Dim ats = item.Attributes




        '        Dim li = .Items.Add(item.Name, liImageIndex)
        '        li.SubItems.Add(newName)

        '        li.SubItems.Add(item.Directory.FullName)


        '    Next
        '    For Each col As ColumnHeader In .Columns
        '        col.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)

        '    Next
        'End With
    End Sub

    
End Class
